﻿
var dashboardModel = new function () {

    this.CalendarList = ko.observableArray(data.CalendarList);
    this.TimeEvent = ko.observable(data.TimeSelected);
    this.UserId = ko.observable(data.UserId);
    this.UserOptions = ko.observableArray(data.UserList);
    this.HideCalendar = ko.observable(false);
    var StartNow = new Date();
    this.onDateSelected = ko.observable(StartNow.getDate() + "/" + (StartNow.getMonth() + 1) + "/" + StartNow.getFullYear());
    this.ShowCalendar = ko.observable(true);
    this.ShowToolbar = ko.observable(true);
    this.ShowPanel = ko.observable(true);
    this.ShowUserList = ko.observable(data.IsAdmin);
    this.ItemsOnCalendar = ko.observableArray(data.CalendarList);
    this.CheckItemsOnCalendar = ko.computed(function () {        
        // Build a function to get data
        var dataPost = { "userId": this.UserId(), "dateSelected": this.onDateSelected() };
        if (this.HideCalendar()) {
            openProcess();
            // Ajax request
            $.ajax({
                type: "POST",
                url: "/Dashboard/GetCalendarEvent",
                data: dataPost,
                dataType: "json",
                success: function (model, textStatus, jqXHR) {
                    dashboardModel.HideCalendar(false);
                    if (model != null && model.Error == undefined || model.Error == null) {
                        if (model != "") {
                            closePopup();
                            hideProcess();
                            dashboardModel.CalendarList(model.CalendarList);
                            dashboardModel.TimeEvent(model.TimeSelected);
                            dashboardModel.ItemsOnCalendar(dashboardModel.CalendarList());
                        }
                        else {
                            showPopupErrorDashboard();
                        }
                        // Resize width of section with screen
                        hscroll_resize_events();
                    }
                    else {
                        showPopupErrorDashboard();
                    }
                },
                error: function (xhr, status, error) {
                    showPopupErrorDashboard();
                }
            });
            this.ItemsOnCalendar(this.CalendarList());
        }
        else {
            this.HideCalendar(true);
        }

    }, this);

    $(document).on("change", "#calendar", function () {
        dashboardModel.onDateSelected($(this).val());
    })

    this.expCalendar = function () {
        if (this.ShowCalendar()) {
            this.ShowCalendar(false);
            this.ShowToolbar(false);
            this.ShowPanel(false);
            $('#expDashboardCalendar').removeAttr("expander");
            $('#expDashboardCalendar').attr("class", "unexpander");

            $('#expDashboardEvent').removeAttr("expander");
            $('#expDashboardEvent').attr("class", "unexpander");
        }
        else {
            this.ShowCalendar(true);
            this.ShowToolbar(true);
            this.ShowPanel(true);
            $('#expDashboardCalendar').removeAttr("unexpander");
            $('#expDashboardCalendar').attr("class", "expander");

            $('#expDashboardEvent').removeAttr("unexpander");
            $('#expDashboardEvent').attr("class", "expander");
        }
    }
    this.ExpanEvents = function () {
        if (this.ShowCalendar()) {
            this.ShowCalendar(false);
            this.ShowToolbar(false);
            this.ShowPanel(false);
            $('#expDashboardCalendar').removeAttr("expander");
            $('#expDashboardCalendar').attr("class", "unexpander");

            $('#expDashboardEvent').removeAttr("expander");
            $('#expDashboardEvent').attr("class", "unexpander");
        }
        else {
            this.ShowCalendar(true);
            this.ShowToolbar(true);
            this.ShowPanel(true);
            $('#expDashboardCalendar').removeAttr("unexpander");
            $('#expDashboardCalendar').attr("class", "expander");

            $('#expDashboardEvent').removeAttr("unexpander");
            $('#expDashboardEvent').attr("class", "expander");
        }
    }
};


var milestoneModel = new function () {

    this.CreditLead = ko.observable("all");
    this.CreditLeadOptions = ko.observableArray(data.LeadSourceList);

    this.CreditUsers = ko.observable("all");
    this.CreditUsersOptions = ko.observableArray(data.MetricUserList);

    this.CreditDate = ko.observable(data.RangeList == null ? 0 : data.RangeList[0].ID);
    this.CreditDateOptions = ko.observableArray(data.RangeList);

    this.MilestoneNone = ko.observable(data.MilestoneModel.None);
    this.MilestoneContacted = ko.observable(data.MilestoneModel.Contacted);
    this.MilestoneRate = ko.observable(data.MilestoneModel.Rate);

    this.ShowToolbar = ko.observable(true);
    this.ShowPanel = ko.observable(true);
    this.ShowUserList = ko.observable(data.IsAdmin);

    this.CheckdropdownUser = ko.computed(function () {

        if (data.IsAdmin) {
            $('#app-body').addClass('dashboard-admin');
        }
        else {
            $('#selectLead').addClass('user');
            $('#selectLead').parent().addClass('user');
            $('#selectLead').parent().children('.editable-select').addClass('user');

            $('#app-body').addClass('dashboard-user');
            $('#selectLead').removeAttr("style");
            $('#ddlAllLeadSources').removeAttr("style");
        }
        return false;
    }, this)

    // Define varials to handle filter section
    this.RangeOption = ko.observable("true");
    this.FromDateEnable = ko.computed(function () {
        if (this.RangeOption() == "false")
            return true;

        return;
    }, this);
    this.RangeEnable = ko.computed(function () {
        if (this.RangeOption() == "true")
            return true;
        return;
    }, this);
    this.ToDateEnable = ko.computed(function () {
        if (this.RangeOption() == "false")
            return true;

        return;
    }, this);

    this.search = function () {
        var dataPost = {
            "sourceId": $("#selectLead").editableSelect('value'),
            "userId": $("#selectUsers").editableSelect('value'),
            "checkRange": milestoneModel.RangeOption(),
            "range": milestoneModel.CreditDate(),
            "startDate": $('#startDate').val(),
            "endDate": $('#endDate').val()
        };

        var urlPost = "/Dashboard/MilestoneReport";

        openProcess();
        // Ajax request
        $.ajax({
            type: "POST",
            url: urlPost,
            data: dataPost,
            dataType: "json",
            success: function (model, textStatus, jqXHR) {
                if (model != null && model.Error == undefined || model.Error == null) {
                    closePopup();
                    hideProcess();
                    if (model != "") {
                        milestoneModel.MilestoneNone(model.None);
                        milestoneModel.MilestoneContacted(model.Contacted);
                        milestoneModel.MilestoneRate(model.Rate);
                    }
                    else {
                        showPopupErrorDashboard();
                    }
                }
                else {
                    showPopupErrorDashboard();
                }
            },
            error: function (xhr, status, error) {
                showPopupErrorDashboard();
            }
        });
    }

    this.expMilestone = function () {
        if (this.ShowToolbar()) {
            this.ShowToolbar(false);
            this.ShowPanel(false);
            $('#expMilestoneMetrics').removeAttr("expander");
            $('#expMilestoneMetrics').attr("class", "unexpander");
        }
        else {
            this.ShowToolbar(true);
            this.ShowPanel(true);
            $('#expMilestoneMetrics').removeAttr("unexpander");
            $('#expMilestoneMetrics').attr("class", "expander");
        }
    }
};

var leadflowModel = new function () {
    this.vsbExp = ko.observable(true);
    this.TimeUpdate = ko.observable(data.LeadFlowModel == null ? "" : data.LeadFlowModel.TimeUpdate);
    this.FlowName = ko.observable("Trạng thái");
    this.listFlow = ko.observableArray(data.LeadFlowModel == null ? [] : data.LeadFlowModel.StatusSummaryInfo);
    this.setcreoll = ko.observable("scroll");
    this.ShowToolbar = ko.observable(true);
    this.visibleflow = ko.observable(true);
    this.ShowUserList = ko.observable(data.IsAdmin);
    this.maxFlow = ko.observable(50);
    this.ItemsOnPage = ko.observableArray([]);
    this.reloadFlow = function () {
        var urlPost = "/Dashboard/LeadFlow";
        openProcess()
        // Ajax request
        $.ajax({
            type: "POST",
            url: urlPost,
            data: {"IsAdmin": this.ShowUserList(), "UserId": data.Header.UserId},
            dataType: "json",
            success: function (model, textStatus, jqXHR) {
                hideProcess();

                if (model == null) {
                    showPopupErrorDashboard();
                }
                else {
                    if (model != "") {
                        if ($("#currentStatus").attr("class") == "area button current") {
                            leadflowModel.FlowName("Trạng thái");
                            leadflowModel.listFlow(model.StatusSummaryInfo);
                        }
                        else {
                            leadflowModel.FlowName("Nguồn khách hàng");
                            leadflowModel.listFlow(model.CampaignSummaryInfo);
                        }
                        leadflowModel.TimeUpdate(model.TimeUpdate);
                    }
                    else {
                        showPopupErrorDashboard();
                    }
                }
            },
            error: function (xhr, status, error) {
                showPopupErrorDashboard();
            }
        });

        return false;
    }

    this.ShowToolBar = ko.computed(function () {
        if (data.IsAdmin) {
            return this.ShowToolbar();
        }
        else {
            return false;
        }
    }, this);

    this.CheckItemsOnPage = ko.computed(function () {
        if (typeof this.listFlow() != 'undefined') {
            this.ItemsOnPage([]);
            this.ItemsOnPage(this.listFlow().slice(0, this.maxFlow()));
        }
    }, this);

    this.showCampaign = function () {
        leadflowModel.FlowName("Nguồn khách hàng");
        leadflowModel.listFlow(data.LeadFlowModel.CampaignSummaryInfo);
        leadflowModel.maxFlow(data.LeadFlowModel.CampaignSummaryInfo.length);
        $("#currentStatus").removeAttr("class");
        $("#currentStatus").attr("class", "area button");
        $("#currentCampaign").removeAttr("class");
        $("#currentCampaign").attr("class", "area button current");

        var _FlowHeight = $('#FlowId').height();
        if (_FlowHeight < 265) {
            $('#crollExp').removeAttr("btn btn-un-plus");
            $('#crollExp').attr("class", "btn btn-plus");
            //this.setcreoll("");
        }
    }
    this.showStatus = function () {
        leadflowModel.FlowName("Trạng thái");
        leadflowModel.listFlow(data.LeadFlowModel.StatusSummaryInfo);
        leadflowModel.maxFlow(data.LeadFlowModel.StatusSummaryInfo.length);
        $("#currentStatus").removeAttr("class");
        $("#currentStatus").attr("class", "area button current");
        $("#currentCampaign").removeAttr("class");
        $("#currentCampaign").attr("class", "area button");

        var _FlowHeight = $('#FlowId').height();
        if (_FlowHeight < 265) {
            $('#crollExp').removeAttr("btn btn-un-plus");
            $('#crollExp').attr("class", "btn btn-plus");
            //this.setcreoll("");
        }
    }

    this.crollExp = function () {
        $('#expDashboardFlow').removeAttr("unexpander");
        $('#expDashboardFlow').attr("class", "expander");
        if (!this.ShowToolbar()) {
            this.ShowToolbar(true);
            this.visibleflow(true);
        }
        if (this.setcreoll() == "scroll") {
            var _FlowHeight = $('#FlowId').height();
            if (_FlowHeight > 265) {
                this.setcreoll("");
                $('#crollExp').removeAttr("btn btn-plus");
                $('#crollExp').attr("class", "btn btn-un-plus");
            }
        }
        else {
            this.setcreoll("scroll");
            $('#crollExp').removeAttr("btn btn-un-plus");
            $('#crollExp').attr("class", "btn btn-plus");
        }
    }
    this.expFlow = function () {
        if (this.ShowToolbar()) {
            this.ShowToolbar(false);
            this.visibleflow(false);
            $('#expDashboardFlow').removeAttr("expander");
            $('#expDashboardFlow').attr("class", "unexpander");
            $('#crollExp').removeAttr("btn btn-un-plus");
            $('#crollExp').attr("class", "btn btn-plus");
        }
        else {
            this.ShowToolbar(true);
            this.visibleflow(true);
            $('#expDashboardFlow').removeAttr("unexpander");
            $('#expDashboardFlow').attr("class", "expander");

            if (this.setcreoll() == "scroll") {
                $('#crollExp').removeAttr("btn btn-un-plus");
                $('#crollExp').attr("class", "btn btn-plus");
            }
            else {
                $('#crollExp').removeAttr("btn btn-plus");
                $('#crollExp').attr("class", "btn btn-un-plus");
            }
        }
    }
};

ko.applyBindings(dashboardModel, document.getElementById("calendarEvents"));
ko.applyBindings(milestoneModel, document.getElementById("milestones"));
ko.applyBindings(leadflowModel, document.getElementById("leadflows"));

function OpenPrintCalendarEventWindow() {
	var url = "/Dashboard/PrintCalendarEvent?userId=" + dashboardModel.UserId() + "&startDate=" + dashboardModel.onDateSelected();
	var widthPopup = 968;
	var heightPopup = 500;
	var leftPopup = (screen.width / 2) - (widthPopup / 2);
	var topPopup = (screen.height / 2) - (heightPopup / 2);

	window.open(url, '', 'left=' + leftPopup + ',top=' + topPopup
		+ ',width=' + widthPopup + ',height=' + heightPopup + ',scrollbars=yes,toolbar=0,status=0');
}
function showPopupErrorDashboard() {

	$('#popupErrorRequest').attr("style", "width: 450px");
	$.fancybox($('#popupErrorRequest'), {
		padding: 0,
		closeBtn: false,
		helpers: {
			overlay: {
				opacity: 0.6,
				css: { 'background-color': '#11619d' },
				closeClick: false
			}
		}
	});
}

$(document).ready(function () {
    // contructors
    $("#calendar").datepicker({
        dateFormat: "dd/mm/yyyy"
    });

    
    // load start/end date to filters
    $("#startDate").datepicker({
        dateFormat: "dd/mm/yyyy"
    });
    $("#endDate").datepicker({
        dateFormat: "dd/mm/yyyy"
    });
   /* */
});
